“Add a and b.” Easy enough: return a+b. Then I read the rest of the question. No plus signs. No minus signs. Oh.
For the record, I submitted return a+b and the judge accepted it. That got a laugh out of me. But the question was worth doing properly. It had to handle negative numbers too: 1 and 2 should give 3, while −2 and 3 should give 1.
Split the answer into a sum and a carry
Forget carries for a moment. For each bit, 1 and 1 should give 0, 1 and 0 should give 1, and two zeros should stay zero. That’s XOR. For example, 101 ^ 011 is 010. That’s part of what we need to add 5 and 3, but it’s clearly not 8 yet.
The missing part is easiest to see with 7 and 7. Both are 111 in binary. XOR gives zero because every pair of bits matches. But those three pairs of ones each produce a carry into the next column. AND finds the pairs, and shifting left moves their carries one place over: (111 & 111) << 1 gives 1110, or 14.
So we have two numbers to combine again: the sum without carries and the carries themselves. Keep going until there are no carries left.
1 | def getSum(a,b): |
Then I tried a negative input
Python printed hex(-1) as -0x1. I’d been picturing a fixed-width register full of ones, FFFFFFFF, and Python was cheerfully doing arithmetic without that 32-bit boundary. My workaround was to keep only the low 32 bits at each step:
1 | def getSum(a,b): |
That gave me the unsigned bit pattern I wanted. The last wrinkle was how to read it: if that pattern represents a negative signed integer, convert it back before returning it. The code above is my original attempt at that conversion.



